package org.esgi.transformer.impl;

import org.esgi.model.impl.User;
import org.esgi.model.interfaces.IUser;
import org.esgi.transformer.interfaces.IXMLUserTransformer;
import org.esgi.util.BooleanConverter;
import org.esgi.util.StringEncoder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUserTransformer extends XMLModelTransformer implements IXMLUserTransformer
{	
	public static final String XMLUserNodeName = "user";
	public static final String XMLUserLoginNodeName = "login";
	public static final String XMLUserPwdNodeName = "pwd";
	public static final String XMLUserRulesNodeName = "rules";

	@Override
	public IUser userFromElement(Element e) 
	{
		IUser u = new User();
		NodeList nl = e.getChildNodes();
		for(int i=0 ; i<nl.getLength(); i++)
		{
			Node childNode = nl.item(i);
			if(childNode.getNodeName().equals(this.addDefaultNamespaceToName(XMLUserRulesNodeName)))
			{
				char[] rules = childNode.getFirstChild().getNodeValue().toCharArray();
				u.setIsSuper(BooleanConverter.booleanValue(rules[0]));
				u.setCanCreate(BooleanConverter.booleanValue(rules[1]));
				u.setCanModify(BooleanConverter.booleanValue(rules[2]));
				u.setCanRead(BooleanConverter.booleanValue(rules[3]));
			}
			else if(childNode.getNodeName().equals(this.addDefaultNamespaceToName(XMLUserLoginNodeName)))
			{
				u.setLogin(childNode.getFirstChild().getNodeValue());
			}
			else if(childNode.getNodeName().equals(this.addDefaultNamespaceToName(XMLUserPwdNodeName)))
			{
				u.setPassword(childNode.getFirstChild().getNodeValue());
			}
		}
		return u;
	}

	@Override
	public Element userToElement(IUser u, Document doc) 
	{
		if(u != null && doc != null)
		{
			Element rootNode = doc.createElement(this.addDefaultNamespaceToName(XMLUserNodeName));
			
			Element loginNode = doc.createElement(this.addDefaultNamespaceToName(XMLUserLoginNodeName));
			loginNode.appendChild(doc.createTextNode(u.getLogin()));
			rootNode.appendChild(loginNode);
			
			Element pwdNode = doc.createElement(this.addDefaultNamespaceToName(XMLUserPwdNodeName));
			pwdNode.appendChild(doc.createTextNode(StringEncoder.encode(u.getPassword(), StringEncoder.Algorithm.SHA1)));
			rootNode.appendChild(pwdNode);
			
			Element rulesNode = doc.createElement(this.addDefaultNamespaceToName(XMLUserRulesNodeName));
			rulesNode.appendChild(doc.createTextNode(u.getStringRules()));
			rootNode.appendChild(rulesNode);
			
			return rootNode;
		}
		return null;
	}
}
